export default class BackgroundElement {
  constructor(game, options = {}) {
    this.game = game;
    
    // 位置和尺寸
    this.x = options.x || game.canvas.width;
    this.y = options.y || 0;
    this.width = options.width || 50;
    this.height = options.height || 50;
    
    // 元素类型和外观
    this.type = options.type || 'default';
    this.color = options.color || '#FFFFFF';
    this.layer = options.layer || 'mid'; // 'back', 'mid', 'front'
    
    // 移动和动画属性
    this.speedX = options.speedX || 1; // 横向移动速度
    this.speedY = options.speedY || 0; // 纵向移动速度
    this.opacity = options.opacity !== undefined ? options.opacity : 1;
    this.scale = options.scale || 1;
    
    // 动画效果
    this.animationSpeed = options.animationSpeed || 0.02;
    this.animationTime = Math.random() * 100; // 随机初始相位
    this.animationType = options.animationType || 'none'; // 'none', 'float', 'sway', 'fade'
    this.animationAmplitude = options.animationAmplitude || 5;
    this.swayOffset = 0; // 初始化左右摇摆的偏移量
    
    // 持久性
    this.isOffScreenRemove = options.isOffScreenRemove !== undefined ? options.isOffScreenRemove : true;
    
    // 特殊属性
    this.customRender = options.customRender;
    this.image = options.image;
    
    // 初始化
    this.init();
  }
  
  init() {
    // 根据图层调整速度
    if (this.layer === 'back') {
      this.speedX *= 0.5;
    } else if (this.layer === 'front') {
      this.speedX *= 1.5;
    }
    
    // 保存初始位置用于动画
    this.initialY = this.y;
    
    // 确保所有关键属性有有效值
    if (isNaN(this.x)) this.x = this.game.canvas.width;
    if (isNaN(this.y)) this.y = this.game.canvas.height / 2;
    if (isNaN(this.width) || this.width <= 0) this.width = 50;
    if (isNaN(this.height) || this.height <= 0) this.height = 50;
    if (isNaN(this.speedX)) this.speedX = 1;
    if (isNaN(this.speedY)) this.speedY = 0;
    if (isNaN(this.scale) || this.scale <= 0) this.scale = 1;
    if (isNaN(this.animationSpeed)) this.animationSpeed = 0.02;
    if (isNaN(this.animationTime)) this.animationTime = Math.random() * 100;
    if (isNaN(this.animationAmplitude)) this.animationAmplitude = 5;
    if (isNaN(this.swayOffset)) this.swayOffset = 0;
    
    // 确保透明度在有效范围内
    if (isNaN(this.opacity) || this.opacity < 0 || this.opacity > 1) {
      this.opacity = 1;
    }
    
    // 只有5%概率输出初始化日志，避免日志过多
    if (Math.random() < 0.05) {
      console.log(`背景元素已初始化: 类型=${this.type}, 层级=${this.layer}, 位置=(${this.x},${this.y})`);
    }
  }
  
  update() {
    // 更新位置
    this.x -= this.speedX;
    this.y += this.speedY;
    
    // 更新动画时间
    this.animationTime += this.animationSpeed;
    
    // 应用动画效果（除了sway，其它效果直接改变属性）
    switch (this.animationType) {
      case 'float':
        // 上下浮动
        this.y = this.initialY + Math.sin(this.animationTime) * this.animationAmplitude;
        break;
        
      case 'sway':
        // 左右摇摆 - 不再直接修改x坐标，而是保存偏移量
        this.swayOffset = Math.sin(this.animationTime) * 0.5;
        break;
        
      case 'fade':
        // 透明度变化
        this.opacity = 0.5 + Math.sin(this.animationTime) * 0.3;
        break;
        
      case 'grow':
        // 尺寸变化
        this.scale = this.scale * 0.9 + Math.sin(this.animationTime) * 0.1 + 0.1;
        break;
    }
    
    return this.isOffScreen();
  }
  
  render(ctx) {
    ctx.save();
    
    // 设置透明度
    ctx.globalAlpha = this.opacity;
    
    // 应用摇摆效果的偏移量（如果有）
    const renderX = this.x + (this.swayOffset || 0);
    
    // 使用自定义渲染函数或默认渲染
    if (this.customRender) {
      this.customRender(ctx, this, renderX);
    } else {
      this.renderByType(ctx, renderX);
    }
    
    ctx.restore();
  }
  
  renderByType(ctx, renderX = this.x) {
    switch (this.type) {
      case 'tree':
        this.renderTree(ctx, renderX);
        break;
        
      case 'cloud':
        this.renderCloud(ctx, renderX);
        break;
        
      case 'snowflake':
        this.renderSnowflake(ctx, renderX);
        break;
        
      case 'leaf':
        this.renderLeaf(ctx, renderX);
        break;
        
      case 'flower':
        this.renderFlower(ctx, renderX);
        break;
        
      case 'mountain':
        this.renderMountain(ctx, renderX);
        break;
        
      case 'star':
        this.renderStar(ctx, renderX);
        break;
      
      default:
        // 使用图片或绘制默认矩形
        if (this.image) {
          try {
            ctx.drawImage(
              this.image,
              renderX - this.width / 2,
              this.y - this.height / 2,
              this.width * this.scale,
              this.height * this.scale
            );
          } catch (error) {
            console.error('背景元素图片渲染失败:', error);
            this.renderDefault(ctx, renderX);
          }
        } else {
          this.renderDefault(ctx, renderX);
        }
    }
  }
  
  renderDefault(ctx, renderX = this.x) {
    ctx.fillStyle = this.color;
    ctx.fillRect(
      renderX - this.width / 2,
      this.y - this.height / 2,
      this.width * this.scale,
      this.height * this.scale
    );
  }
  
  renderTree(ctx, renderX = this.x) {
    // 绘制树干
    ctx.fillStyle = '#8B4513'; // 棕色
    ctx.fillRect(
      renderX - this.width / 8,
      this.y + this.height / 4,
      this.width / 4,
      this.height / 2
    );
    
    // 绘制树冠
    ctx.fillStyle = this.color; // 绿色
    ctx.beginPath();
    ctx.moveTo(renderX, this.y - this.height / 2);
    ctx.lineTo(renderX - this.width / 2, this.y + this.height / 4);
    ctx.lineTo(renderX + this.width / 2, this.y + this.height / 4);
    ctx.closePath();
    ctx.fill();
    
    // 再绘制一层树冠
    ctx.beginPath();
    ctx.moveTo(renderX, this.y - this.height / 4);
    ctx.lineTo(renderX - this.width / 2, this.y + this.height / 3);
    ctx.lineTo(renderX + this.width / 2, this.y + this.height / 3);
    ctx.closePath();
    ctx.fill();
  }
  
  renderCloud(ctx, renderX = this.x) {
    ctx.fillStyle = this.color;
    
    // 绘制云朵 - 由多个圆组成
    const centerX = renderX;
    const centerY = this.y;
    const radiusMain = this.width / 3;
    
    ctx.beginPath();
    ctx.arc(centerX, centerY, radiusMain, 0, Math.PI * 2);
    ctx.arc(centerX + radiusMain * 0.8, centerY, radiusMain * 0.7, 0, Math.PI * 2);
    ctx.arc(centerX - radiusMain * 0.8, centerY, radiusMain * 0.6, 0, Math.PI * 2);
    ctx.arc(centerX - radiusMain * 0.3, centerY - radiusMain * 0.4, radiusMain * 0.7, 0, Math.PI * 2);
    ctx.arc(centerX + radiusMain * 0.3, centerY - radiusMain * 0.4, radiusMain * 0.6, 0, Math.PI * 2);
    ctx.closePath();
    ctx.fill();
  }
  
  renderSnowflake(ctx, renderX = this.x) {
    const centerX = renderX;
    const centerY = this.y;
    const size = this.width / 2 * this.scale;
    
    ctx.strokeStyle = this.color;
    ctx.lineWidth = 2;
    
    // 绘制雪花的六个分支
    for (let i = 0; i < 6; i++) {
      const angle = (Math.PI / 3) * i;
      ctx.beginPath();
      ctx.moveTo(centerX, centerY);
      ctx.lineTo(
        centerX + Math.cos(angle) * size,
        centerY + Math.sin(angle) * size
      );
      ctx.stroke();
      
      // 绘制每个分支上的小分支
      for (let j = 1; j <= 2; j++) {
        const branchStartX = centerX + Math.cos(angle) * (size * j / 3);
        const branchStartY = centerY + Math.sin(angle) * (size * j / 3);
        const branchSize = size / 3;
        
        // 左小分支
        ctx.beginPath();
        ctx.moveTo(branchStartX, branchStartY);
        ctx.lineTo(
          branchStartX + Math.cos(angle + Math.PI / 3) * branchSize,
          branchStartY + Math.sin(angle + Math.PI / 3) * branchSize
        );
        ctx.stroke();
        
        // 右小分支
        ctx.beginPath();
        ctx.moveTo(branchStartX, branchStartY);
        ctx.lineTo(
          branchStartX + Math.cos(angle - Math.PI / 3) * branchSize,
          branchStartY + Math.sin(angle - Math.PI / 3) * branchSize
        );
        ctx.stroke();
      }
    }
  }
  
  renderLeaf(ctx, renderX = this.x) {
    const centerX = renderX;
    const centerY = this.y;
    const size = this.width / 2 * this.scale;
    
    ctx.fillStyle = this.color;
    ctx.beginPath();
    
    // 绘制叶子形状
    ctx.ellipse(
      centerX, centerY,
      size, size / 2,
      Math.PI / 4 + Math.sin(this.animationTime) * 0.2, // 随机旋转
      0, Math.PI * 2
    );
    
    ctx.closePath();
    ctx.fill();
    
    // 绘制叶脉
    ctx.strokeStyle = 'rgba(0, 0, 0, 0.2)';
    ctx.lineWidth = 1;
    ctx.beginPath();
    ctx.moveTo(centerX - size * 0.7, centerY - size * 0.3);
    ctx.quadraticCurveTo(
      centerX, centerY,
      centerX + size * 0.7, centerY + size * 0.3
    );
    ctx.stroke();
  }
  
  renderFlower(ctx, renderX = this.x) {
    const centerX = renderX;
    const centerY = this.y;
    const size = this.width / 4 * this.scale;
    
    // 绘制花瓣
    ctx.fillStyle = this.color;
    for (let i = 0; i < 5; i++) {
      const angle = (Math.PI * 2 / 5) * i;
      ctx.beginPath();
      ctx.ellipse(
        centerX + Math.cos(angle) * size,
        centerY + Math.sin(angle) * size,
        size, size / 2,
        angle,
        0, Math.PI * 2
      );
      ctx.fill();
    }
    
    // 绘制花蕊
    ctx.fillStyle = '#FFFF00';
    ctx.beginPath();
    ctx.arc(centerX, centerY, size / 2, 0, Math.PI * 2);
    ctx.fill();
  }
  
  renderMountain(ctx, renderX = this.x) {
    const baseX = renderX - this.width / 2;
    const baseY = this.y + this.height / 2;
    const peakX = renderX;
    const peakY = this.y - this.height / 2;
    
    // 绘制山体
    ctx.fillStyle = this.color;
    ctx.beginPath();
    ctx.moveTo(baseX, baseY);
    ctx.lineTo(peakX, peakY);
    ctx.lineTo(baseX + this.width, baseY);
    ctx.closePath();
    ctx.fill();
    
    // 绘制山顶雪
    if (this.type === 'snow_mountain') {
      ctx.fillStyle = '#FFFFFF';
      ctx.beginPath();
      ctx.moveTo(peakX - this.width / 4, peakY + this.height / 4);
      ctx.lineTo(peakX, peakY);
      ctx.lineTo(peakX + this.width / 4, peakY + this.height / 4);
      ctx.closePath();
      ctx.fill();
    }
  }
  
  renderStar(ctx, renderX = this.x) {
    const centerX = renderX;
    const centerY = this.y;
    const outerRadius = this.width / 2 * this.scale;
    const innerRadius = outerRadius / 2.5;
    const spikes = 5;
    
    ctx.fillStyle = this.color;
    ctx.beginPath();
    
    for (let i = 0; i < spikes * 2; i++) {
      const radius = i % 2 === 0 ? outerRadius : innerRadius;
      const angle = (Math.PI / spikes) * i;
      
      const x = centerX + Math.cos(angle) * radius;
      const y = centerY + Math.sin(angle) * radius;
      
      if (i === 0) {
        ctx.moveTo(x, y);
      } else {
        ctx.lineTo(x, y);
      }
    }
    
    ctx.closePath();
    ctx.fill();
  }
  
  isOffScreen() {
    // 检查元素是否超出屏幕
    if (this.isOffScreenRemove) {
      return (this.x + this.width / 2 < 0 ||
              this.x - this.width / 2 > this.game.canvas.width ||
              this.y + this.height / 2 < 0 ||
              this.y - this.height / 2 > this.game.canvas.height);
    }
    return false;
  }
  
  static createRandomElement(game, type, layer, options = {}) {
    // 创建指定类型的随机位置背景元素
    const canvas = game.canvas;
    let x, y, width, height, color, animationType;
    
    // 根据类型设置默认属性
    switch (type) {
      case 'tree':
        width = 60 + Math.random() * 40;
        height = 100 + Math.random() * 50;
        x = canvas.width + width / 2;
        y = canvas.height - 150 + height / 4; // 放在地面上
        color = options.color || '#228B22'; // 森林绿
        animationType = 'sway';
        break;
        
      case 'cloud':
        width = 80 + Math.random() * 60;
        height = 40 + Math.random() * 30;
        x = canvas.width + width / 2;
        y = 50 + Math.random() * 100; // 天空中
        color = options.color || 'rgba(255, 255, 255, 0.8)';
        animationType = 'float';
        break;
        
      case 'snowflake':
        width = 10 + Math.random() * 15;
        height = width;
        x = Math.random() * canvas.width;
        y = -height;
        color = options.color || '#FFFFFF';
        animationType = 'float';
        options.speedY = 0.5 + Math.random() * 1.5; // 下落速度
        options.speedX = (Math.random() - 0.5) * 0.5; // 轻微的横向偏移
        break;
        
      case 'leaf':
        width = 15 + Math.random() * 10;
        height = width / 2;
        x = canvas.width + width / 2;
        y = 150 + Math.random() * (canvas.height - 300);
        color = options.color || '#8FBC8F'; // 淡绿色
        animationType = 'sway';
        options.speedY = Math.sin(Math.random() * Math.PI) * 0.5; // 轻微的上下飘落
        break;
        
      case 'flower':
        width = 20 + Math.random() * 15;
        height = width;
        x = canvas.width + width / 2;
        y = canvas.height - 150 - Math.random() * 30; // 地面上
        color = options.color || '#FF69B4'; // 粉色
        animationType = 'sway';
        break;
        
      case 'mountain':
        width = 200 + Math.random() * 300;
        height = 100 + Math.random() * 150;
        x = canvas.width + width / 2;
        y = canvas.height - 145 - height / 2; // 地面上
        color = options.color || '#696969'; // 深灰色
        animationType = 'none';
        break;
        
      case 'star':
        width = 5 + Math.random() * 10;
        height = width;
        x = Math.random() * canvas.width;
        y = 30 + Math.random() * 100; // 天空中
        color = options.color || '#FFFF00'; // 黄色
        animationType = 'fade';
        break;
        
      default:
        width = 30;
        height = 30;
        x = canvas.width + width / 2;
        y = canvas.height / 2;
        color = options.color || '#FFFFFF';
        animationType = 'none';
    }
    
    // 根据图层调整速度
    let speedX = 1;
    if (layer === 'back') {
      speedX = 0.5;
    } else if (layer === 'front') {
      speedX = 1.5;
    }
    
    // 创建元素
    return new BackgroundElement(game, {
      x,
      y,
      width,
      height,
      type,
      color,
      layer,
      speedX: options.speedX !== undefined ? options.speedX : speedX,
      speedY: options.speedY !== undefined ? options.speedY : 0,
      opacity: options.opacity !== undefined ? options.opacity : 1,
      scale: options.scale || 1,
      animationType: options.animationType || animationType,
      animationSpeed: options.animationSpeed || 0.02,
      animationAmplitude: options.animationAmplitude || 5,
      isOffScreenRemove: options.isOffScreenRemove !== undefined ? options.isOffScreenRemove : true,
      customRender: options.customRender,
      image: options.image
    });
  }
} 